package com.yunxi.rocketmq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.aliyun.openservices.ons.api.*;
import com.yunxi.claim.pojo.CmLabourBasicStepReqVO;
import com.yunxi.claim.pojo.CmLabourStepReqVO;
import com.yunxi.claim.service.CmLabourBasicStepDubboService;
import com.yunxi.claim.service.CmLabourStepDubboService;
import com.yunxi.core.base.Constant;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.eai.pojo.cms.BaseManHourStepVO;
import com.yunxi.eai.pojo.cms.ManHourStepVO;
import com.yunxi.eai.pojo.esb.EsbVO;
import com.yunxi.model.eai.EaiLog;
import com.yunxi.rocketmq.config.CmsBaseManHourStepRocketMQConfig;
import com.yunxi.rocketmq.config.CmsHourStepRocketMQConfig;
import com.yunxi.rocketmq.producer.EaiLogsProducer;
import com.yunxi.service.eai.EaiLogService;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * Created by Administrator on 2019/9/25.
 */
@Component
public class CmsBaseManHourStepConsumer implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger logger = LoggerFactory.getLogger(CmsBaseManHourStepConsumer.class);
    @Autowired
    private CmsBaseManHourStepRocketMQConfig cmsBaseManHourStepRocketMQConfig;
    @Value("${aliyun.rocketMQ.cms.base.man.hour.step.topic}")
    private String topic;
    @Value("${aliyun.rocketMQ.cms.base.man.hour.step.tag}")
    private String tag;
    @Value("${aliyun.rocketMQ.cms.base.man.hour.step.group}")
    private String group;
    @Autowired
    CmLabourBasicStepDubboService cmLabourBasicStepDubboServiceImpl;
    @Autowired
    @Qualifier("eaiLogServiceImpl")
    EaiLogService eaiLogService;
    @Autowired
    private Mapper dozerMapper;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        Properties properties = cmsBaseManHourStepRocketMQConfig.getProperties();
        properties.put(PropertyKeyConst.GROUP_ID, group);
        // 集群订阅方式设置（不设置的情况下，默认为集群订阅方式）
        properties.put(PropertyKeyConst.MessageModel, PropertyValueConst.CLUSTERING);
        Consumer consumer = ONSFactory.createConsumer(properties);
        consumer.subscribe(topic, tag, new MessageListener() {
            @Override
            public Action consume(Message message, ConsumeContext context) {
                System.out.println(tag + " Receive: " + new String(message.getBody()));
                try {
                    String cmsManHourStep = new String(message.getBody(), "utf-8");
                    EsbVO esbVO = JSON.parseObject(cmsManHourStep, EsbVO.class);
                    ApiResult apiResult = null;
                    String reqBody = esbVO.getReqBody();
                    ArrayList<BaseManHourStepVO> baseManHourStepList = JSON.parseObject(reqBody, new TypeReference<ArrayList<BaseManHourStepVO>>() {
                    });
                    EaiLog eaiLog = new EaiLog();
                    eaiLog.setRequestId(esbVO.getRequestId());
                    eaiLog.setEsbEaiContent(reqBody);
                    eaiLog.setEsbEaiText(reqBody);
                    eaiLog.setCreateDate(new Date());
                    eaiLog.setRequestSendTime(new Date());
                    eaiLog.setFlowDesc("CMS传递工时基础步骤信息给PMS");
                    eaiLog.setSourceSystem(Constant.PMS);
                    eaiLog.setServiceName(esbVO.getServiceName());
                    try {
                        //调用内部接口
                        List<CmLabourBasicStepReqVO> var1 = new ArrayList<>();
                        for (int i = 0; i < baseManHourStepList.size(); i++) {
                            CmLabourBasicStepReqVO cmLabourBasicStepReqVO = dozerMapper.map(baseManHourStepList.get(i), CmLabourBasicStepReqVO.class);
                            var1.add(cmLabourBasicStepReqVO);
                        }
                        cmLabourBasicStepDubboServiceImpl.saveOrUpdateBatch(var1);
                        eaiLog.setResponseReceiveTime(new Date());
                        eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                        eaiLog.setDisposeStatus(2);
                    }
                        eaiLogService.saveOrUpdate(eaiLog);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                return Action.CommitMessage;
            }
        });
        consumer.start();
        System.out.println("工时基础步骤信息消费者启动===========");
    }
}
